/**
 *@NApiVersion 2.x
 *@NScriptType ClientScript
 */
define(['N/record', 'N/search', 'N/ui/dialog',], function (record, search, dialog) {
    var woId, processTypeId, componentLineCount, startoperation, startoperationText, operationtaskResults;

    function pageInit(context) {
        woId = context.currentRecord.getValue('createdfrom');
        var operationtaskSearch = search.create({
            type: 'manufacturingoperationtask',
            columns: ['completedquantity'],
            filters: [['workorder', 'is', woId]]
        });
        operationtaskResults = operationtaskSearch.run().getRange(0, 100);

        componentLineCount = context.currentRecord.getLineCount('component');
        context.currentRecord.getField('endoperation').isDisabled = true;
        context.currentRecord.getField('custbody_iscreatetransferinventory').isDisplay = false;
    }

    function fieldChanged(context) {
        if (context.fieldId === 'startoperation') {//开始操作,结束操作一致
            startoperation = context.currentRecord.getValue('startoperation');
            context.currentRecord.setValue('endoperation', startoperation);
            startoperationText = context.currentRecord.getText('startoperation');
            if (startoperationText.length > 0) {
                processTypeId = getProcessTypeIdByOperationTaskId(startoperation);
                if (processTypeId === '1' || processTypeId === '2' || processTypeId === '3') {
                    dialog.alert({title: "提示", message: "委外工序不能直接耗料!"});
                    context.currentRecord.setText('startoperation', '');
                } else {
                    for (var i = 0; i < componentLineCount; i++) {
                        var itemId = context.currentRecord.getSublistValue('component', 'item', i);
                        if (itemId === '868' || itemId === '49' || itemId === '866') {//材料加工费、材料深加工费或工序加工费
                            context.currentRecord.selectLine('component', i);
                            context.currentRecord.setCurrentSublistValue('component', 'quantity', 0);
                            context.currentRecord.commitLine('component');
                            context.currentRecord.getSublistField('component', 'quantity', i).isDisabled = true;
                        }
                    }
                    if (Number(startoperationText) !== 1) {
                        var woRec = record.load({type: 'workorder', id: woId, isDynamic: true});
                        var bomRevisionId = woRec.getValue('billofmaterialsrevision');
                        //上道工序的完工数量之和 - 本道工序的报工数量之和,  >0,填在完工数量,<=0 alert,setText
                        var processNum = Number(startoperationText);
                        if (processNum !== 1) {
                            //获得上道工序完工数量
                            var predecessorCompletedquantity = Number(operationtaskResults[processNum - 2].getValue('completedquantity'));
                            //查找当前工序报工数量
                            var currentReportquantity = 0;
                            search.create({
                                type: 'workordercompletion',
                                columns: ['custbody_reportwork_qty'],
                                filters: [['createdfrom', 'is', woId], 'and', ['mainline', 'is', 'T'], 'and', ['custbody_wo_processnum', 'equalto', processNum]]
                            }).run().each(function (result) {
                                currentReportquantity += Number(result.getValue('custbody_reportwork_qty'));
                                return true;
                            });
                        }
                        dialog.alert({
                            title: "提示",
                            message: "上道工序完工数量:" + predecessorCompletedquantity + ",本道工序报工数量:" + currentReportquantity + "!"
                        });

                        var subtractQuantity = predecessorCompletedquantity - currentReportquantity;// 上道工序完成数量 - 本道工序报工数量
                        if (subtractQuantity > 0) {
                            for (var i = 0; i < componentLineCount; i++) {
                                var operationsequencenumber = context.currentRecord.getSublistText('component', 'operationsequencenumber', i);
                                if (Number(processNum) === Number(operationsequencenumber)) {
                                    var itemId = context.currentRecord.getSublistValue('component', 'item', i);
                                    if (itemId !== '868' && itemId !== '49' && itemId !== '866') {
                                        var bomQuantity = getCurrentProcessCurrentItemBomQuantity(bomRevisionId, itemId);
                                        context.currentRecord.selectLine('component', i);
                                        context.currentRecord.setCurrentSublistValue('component', 'quantity', bomQuantity * subtractQuantity);
                                        context.currentRecord.commitLine('component');
                                    }
                                }
                            }
                        } else {
                            context.currentRecord.setValue('startoperation', '');
                        }

                    }
                }
            }
        }
    }

    function saveRecord(context) {
        try {
            if (!context.currentRecord.getText('startoperation')) {
                dialog.alert({title: "提示", message: "请选择开始操作!"});
                return false;
            }
            var locationId = context.currentRecord.getValue('location');
            var locationName = context.currentRecord.getText('location');
            if (locationId && processTypeId === '4') {
                for (var i = 0; i < componentLineCount; i++) {
                    var itemId = context.currentRecord.getSublistValue('component', 'item', i);
                    if (itemId !== '868' && itemId !== '49' && itemId !== '866') {
                        var rec = record.load({type: 'inventoryitem', id: itemId, isDynamic: true});
                        var itemName = rec.getText('itemid');
                        var quantity = context.currentRecord.getSublistValue('component', 'quantity', i);
                        var binnumberLineNumber = rec.findSublistLineWithValue('binnumber', 'binnumber', 3);//线边仓生产区
                        if (binnumberLineNumber !== -1) {//找到了[线边仓生产区]库位
                            var binnumberQuantityavailable = rec.getSublistValue('binnumber', 'onhandavail', binnumberLineNumber);
                            if (parseFloat(quantity) > parseFloat(binnumberQuantityavailable)) {
                                dialog.alert({
                                    title: "提示",
                                    message: "库存不足,无法耗料!第" + (i + 1) + "行货品[" + itemName + "]在[线边仓-生产区]的库存可用数量为" + binnumberQuantityavailable
                                });
                                return false;
                            }
                        } else {//没找到[线边仓生产区]库位
                            var locationLineNumber = rec.findSublistLineWithValue('locations', 'location', locationId);
                            if (locationLineNumber !== -1) { // 找到了[线边仓]仓库 可用数量
                                var quantityavailable = rec.getSublistValue('locations', 'quantityavailable', lineNumber);
                                if (parseFloat(quantity) > parseFloat(quantityavailable)) {
                                    dialog.alert({
                                        title: "提示",
                                        message: '库存不足,无法耗料!第' + (i + 1) + '行货品[' + itemName + ']在[' + locationName + ']的库存可用数量为:' + quantityavailable
                                    });
                                    return false;
                                }
                            } else {//没找到[线边仓]仓库 可用数量
                                dialog.alert({
                                    title: "提示",
                                    message: '库存不足,无法耗料!第' + (i + 1) + '行货品[' + itemName + ']在[' + locationName + ']没有库存!'
                                });
                                return false;
                            }
                        }
                    }
                }
            }
            dialog.alert({title: "提示", message: '正在处理,请稍候!'});
            //获得总账影响唯一标识
            var results = search.create({
                type: 'workorderissue',
                columns: [],
                filters: [['createdfrom', 'is', woId],
                    'and', ['mainline', 'is', 'T'],
                    'and', ['custbody_wo_processnum', 'equalto', Number(context.currentRecord.getText('startoperation'))]]
            }).run().getRange(0, 100);
            context.currentRecord.setValue('custbody_identify', results.length + 1);
            context.currentRecord.setValue('custbody_wo_processnum', Number(context.currentRecord.getText('startoperation')));
        } catch (e) {
        }
        return true;
    }

    function getProcessTypeIdByOperationTaskId(operationTaskId) {
        var fieldLookUp1 = search.lookupFields({
            type: 'manufacturingoperationtask',
            id: operationTaskId,
            columns: ['manufacturingcosttemplate']
        });
        var manufacturingcosttemplateId = fieldLookUp1.manufacturingcosttemplate[0].value;
        var fieldLookUp2 = search.lookupFields({
            type: 'manufacturingcosttemplate',
            id: manufacturingcosttemplateId,
            columns: ['custrecord_processtype']
        });
        return fieldLookUp2.custrecord_processtype[0].value;
    }


    function getCurrentProcessCurrentItemBomQuantity(bomRevisionId, itemId) {
        var bomRevision = record.load({
            type: record.Type.BOM_REVISION,
            id: bomRevisionId,
            isDynamic: true
        });
        for (var i = 0; i < bomRevision.getLineCount('component'); i++) {
            var comItemId = bomRevision.getSublistValue('component', 'item', i);
            if (itemId == comItemId) {
                var bomQuantity = bomRevision.getSublistValue('component', 'bomquantity', i);
                return bomQuantity;
            }
        }
        return 0;
    }

    return {
        pageInit: pageInit,
        fieldChanged: fieldChanged,
        saveRecord: saveRecord
    };
});